from flask import request

from api.libs.RedPrint import RedPrint
from core.documents import SqlModel

api = RedPrint('sql')


@api.route('/list')
def sql_list():
    from core.documents import SqlModel
    return [item.table_name for item in SqlModel.objects()]


@api.route('/build', methods=['POST'])
def sql_build():
    content = request.form['content']
    SqlModel.rebuild(content)
    return True


@api.route('/fields')
def sql_fields():
    table_name = request.values['table']
    model = SqlModel.objects(table_name=table_name).first()
    res = []
    for key in model.fields:
        res.append({'name': key, 'cons': ' '.join(model.fields[key])})
    return res


@api.route('/constraint')
def sql_constraint():
    table_name = request.values['table']
    model = SqlModel.objects(table_name=table_name).first()
    res = []
    for key in model.constraint:
        res.append({'content': key})
    return res
